from django.shortcuts import render

# Create your views here.

from django.shortcuts import get_object_or_404
from rest_framework import viewsets, status
from rest_framework.response import Response
from rest_framework.decorators import action
from django.http.request import QueryDict

from .serializers import AnalyseSerializer
from .models import analyse

from .analyse_live import Live


class AnalyseViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    queryset = analyse.objects.all()
    serializer_class = AnalyseSerializer

    live = Live()

    # {pullrtsp, pushrtmp, pushflv, aichoice, aipushstream, aipushsubimg}
    @action(methods=['post'], detail=False)
    def push_stream(self, request, *args, **kwargs):
        pullrtsp = request.data.get('pullrtsp', None)
        aichoice = request.data.get('aichoice', 'face')
        aipushstream = request.data.get('aipushstream', False)
        aipushsubimg = request.data.get('aipushsubimg', False)
        self.live.set_params(pullrtsp, aichoice, aipushstream, aipushsubimg)
        if self.live.pullrtsp:
            self.live.run()
        live_params = self.live.get_params()
        return Response(live_params, status=status.HTTP_200_OK)
    
    @action(methods=['post'], detail=False)
    def close_stream(self, request, *args, **kwargs):
        self.live.stop_thread()
        return Response({}, status=status.HTTP_200_OK)
    
    @action(methods=['get'], detail=False)
    def get_params(self, request, *args, **kwargs):
        live_params = self.live.get_params()
        return Response(live_params, status=status.HTTP_200_OK)
